package com.yangit.temp.util.excel.easy.util;

import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.yangit.temp.util.excel.easy.entity.StationData;
import com.yangit.temp.util.excel.easy.mapper.StationDataMapper;

import java.util.List;



@Component
public class StationBatchUtil{


	@Autowired
	SqlSessionTemplate sqlSessionTemplate;

	private static final int BATCH_COUNT = 500;

	private String methodName = StationDataMapper.class.getName()+".addSome";

	@Async
	public void saveData(List<StationData> list) {
	
		// 新获取一个模式为BATCH，自动提交为false的session
		// 如果自动提交设置为true,将无法控制提交的条数，改为最后统一提交，可能导致内存溢出

		if(null==sqlSessionTemplate) {
			System.out.println("error---------------------------------");
			this.sqlSessionTemplate = SpringUtil.getBean(SqlSessionTemplate.class);
		}
		SqlSession session = this.sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH,false);
		try {
			if (null!=list && list.size() > 0) {
				int lsize = list.size();
				for (int i = 0, n = list.size(); i < n; i++) {
					StationData obj = list.get(i);

					// "包名+类名+方法名"
					// session.update("com.xx.mapper.UserMapper.updateByPrimaryKeySelective",_entity);
					session.insert(methodName, obj);
					if ((i > 0 && i % BATCH_COUNT == 0) || i == lsize - 1) {
						// 手动每2000个一提交，提交后无法回滚
						session.commit();
						// 清理缓存，防止溢出
						session.clearCache();
					}
				}
			}
		} catch (Exception e) {
			// 没有提交的数据可以回滚
			session.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

}
